from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
import jwt
from werkzeug.security import check_password_hash, generate_password_hash
from users.models import *
import time
from django.conf import settings
import json
from django.core.paginator import Paginator


# Create your views here.


# 登入
class UserView(APIView):
    def post(self, request):
        # 获取前端数据
        username = request.data.get('username')
        password = request.data.get('password')

        if not all([username, password]):
            return Response({
                'code': 400,
                'message': '获取的数据为空'
            })
        try:
            user = UserModel.objects.get(username=username)
        except Exception as e:
            print('>>>>>>>>>', e)
            return Response({
                'code': 400,
                'message': '没有此用户'
            })

        if check_password_hash(user.password, password):
            token = jwt.encode({
                'uid': user.id,
                'username': user.username,
                'exp': time.time() + 720000
            }, key=settings.SECRET_KEY, algorithm='HS256')

            return Response({
                'code': 200,
                'message': '登入成功',
                'data': {
                    'token': token,
                    "character": '大佬',
                    'uid': user.id
                },

            })
        return Response({
            'code': 400,
            'message': '密码错误'
        })


# 获取信息
class GUserView(APIView):
    def get(self, request):
        # 接受前端token
        deng = request.query_params.get('token')
        key = settings.SECRET_KEY
        token = jwt.decode(deng, key=key, algorithms='HS256')
        print('token的', token)

        u_id = token.get("uid")
        print('dasdasd', u_id)

        try:
            user = UserModel.objects.get(id=u_id)
        except Exception as e:
            print('>>>>>>>>>', e)
            return Response({
                'code': 400,
                'message': '获取失败'
            })

        return Response({
            'code': 200,
            'message': '获取成功',
            'data': {
                'roles': '超级用户',
                'name': user.username,
                'avatar': user.portrait,
            }

        })


# 退出登入
class LogoutView(APIView):
    def post(self, request):
        return Response({
            "code": 200,
            "message": "退出登录成功"
        })


class MenusView(APIView):
    def get(self, request):
        return Response({
            'code': 200,
            'message': '成功',
            'detail': [{
                'id': 1,
                'name': 'Cate',
                'path': '/user',
                'redirect': '/example/table',
                'component': 'user/user',
                'alwaysShow': True,
                'meta': {
                    'title': '涛涛管理',
                    'icon': 'el-icon-setting',
                },
                'pid': None,
                'sort': 0,
                'children': [{
                    'id': 2,
                    'name': 'user',
                    'path': '/user',
                    "component": "user/user",
                    'meta': {
                        'title': '用户管理',
                        'icon': 'el-icon-setting',
                    },

                    'pid': None,
                    'sort': 0,
                }, {
                    'path': '/department',
                    'name': 'department',
                    'component': 'user/department',
                    'meta': {'title': '客户管理', 'icon': 'el-icon-user-solid'}
                }]
            }]
        })


# 获取用户信息
class UserGetView(APIView):
    def get(self, request):

        currentPage = request.query_params.get('page')
        pageSize = request.query_params.get('page_size')
        name = request.query_params.get('name')

        # print('>>>>><><><><',name)
        name = json.loads(name)
        bus = UserModel.objects.all()
        if name['name']:
            bus = bus.filter(name=name['name'])
        if name['mobile']:
            bus = bus.filter(mobile=name['mobile'])

        # bus = bus.filter(delete=False)

        # 分页数据
        paginator = Paginator(bus, pageSize)
        # 获取当前页面  currentPage：页码
        page = paginator.page(currentPage)

        # 获取当前页面中的数据(商品对象) object_list:查询集
        data = page.object_list

        user_list = []

        for i in data:
            user_list.append({
                'uid': i.id,
                'username': i.username,
                'name': i.name,
                'role': i.role_id,
                'role_name': i.role.role_name,
                'birthday': i.birthday,
                'job': i.job_id,
                'job_name': i.job.job_name,
                'rank': i.rank_id,
                'rank_name': i.rank.rank_name,
                'mobile': i.mobile,
                'region': i.region,
                'department': i.department_id,
                'department_name': i.department.department_name,
                'mailbox': i.mailbox,
                'portrait': i.portrait,
                'gender': i.gender,
                'operating_time': datetime.strftime(i.operating_time, '%y-%m-%d %H:%M:%S'),
            })

        return Response({
            'code': 200,
            'message': '获取成功',
            'data': user_list,
            'total': bus.count()
        })

    def post(self, request):
        ...


# 获取用户单个信息，删除用户修改用户
class UserInfoModel(APIView):
    def get(self, request, id):
        ...

    def put(self, request, id):
        ...

    def delete(self, request, id):
        ...


# 获取角色，添加角色
class RoleView(APIView):
    def get(self, request):
        currentPage = request.query_params.get('page')
        pageSize = request.query_params.get('page_size')
        name = request.query_params.get('name')

        # print('>>>>><><><><',name)
        name = json.loads(name)
        bus = RoleModel.objects.all()
        if name['name']:
            bus = bus.filter(role_name=name['name'])

        # 分页数据

        paginator = Paginator(bus, pageSize)

        # 获取当前页面  currentPage：页码

        page = paginator.page(currentPage)

        # 获取当前页面中的数据(商品对象) object_list:查询集
        data = page.object_list

        user_list = []

        for i in data:
            user_list.append({
                'rid': i.id,
                'role_name': i.role_name,
            })

        return Response({
            'code': 200,
            'message': '获取成功',
            'data': user_list,
            'total': bus.count()
        })

    def post(self,request):
        # 接受前端数据
        role_name = request.data.get('role_name')

        RoleModel.objects.create(
            role_name=role_name
        )

        return Response({
            'code':200,
            'message':'添加成功'
        })

# 获取单个角色
class RoleInfoView(APIView):
    def get(self,request,id):
        try:
            role = RoleModel.objects.get(id=id)
            print('>>>>>>',role.role_name)
        except Exception as e:
            print('>>>>>>>>',e)

        return Response({
            'code':200,
            'message':'获取成功',
            'data':{
                'id':role.id,
                'role_name':role.role_name
            }
        })

    def put(self,request,id):
        # 接受前端数据
        role_name = request.data.get('role_name')

        try:
            role = RoleModel.objects.get(id=id)
            print('>>>>>>',role.role_name)
        except Exception as e:
            print('>>>>>>>>',e)

        role.role_name = role_name
        role.save()

        return Response({
            'code':200,
            'message':'修改成功'
        })

    # 删除
    def delete(self,request,id):
        try:
            RoleModel.objects.get(id=id).delete()
            return Response({
                'code':200,
                'message':'删除成功'
            })
        except Exception as e:
            print('>>>>>>>>',e)

            return Response({
                'code':400,
                'message':'删除失败'
            })



